﻿using Authentication.Core.Configuration;
using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data.Repository.Enum;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Authentication.Core.ServiceCommand.ChangeDao
{
    public class RetrieveListChangeDaoRequestServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveListChangeDaoRequestRequest, RetrieveListChangeDaoRequestResponse>
    {

        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        public string TextSearch;
        public FilterRecord Filter = null;
        private UserRecord currentUser;
        public RetrieveListChangeDaoRequestServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveListChangeDaoRequestRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.CurrentUser == null)
            {
                throw new ArgumentException("User record must be set", "request");
            }
            else
            {
                currentUser = request.CurrentUser;
            }
            Filter = Request.Filter;
        }

        protected override bool OnExecute(RetrieveListChangeDaoRequestResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            var applicationKey = Request.Header.ApplicationKey;
            try
            {
                if (Request.Page != null)
                {
                    pageIndex = Request.Page.PageIndex ?? 0;
                    pageSize = Request.Page.PageSize ?? 0;
                }
                List<ChangeDaoRequest> listUser = new List<ChangeDaoRequest>();
                if (currentUser.GroupIdentifier.Equals("4") || currentUser.Position.Equals("SBOM") || currentUser.Position.Equals("MBOM") || currentUser.Position.Equals("TeamLead"))
                {
                    List<ChangeDaoCif> listDaoCif = Providers.ChangeDao.RetrieveChangeDaoCifByDao(currentUser);
                    List<ChangeDaoProductChecked> listDaoProduct = Providers.ChangeDao.RetrieveListChangeDaoProductByDao(currentUser);
                    List<int> listChangeDaoId = new List<int>();
                    if (listDaoCif != null && listDaoCif.Count > 0)
                    {
                        listChangeDaoId.AddRange(listDaoCif.Select(x => x.ChangeDaoId).Distinct().ToList());
                    }
                    if (listDaoProduct != null && listDaoProduct.Count > 0)
                    {
                        listChangeDaoId.AddRange(listDaoProduct.Select(x => x.ChangeDaoRequestId.Value).Distinct().ToList());
                    }
                    listUser = Providers.ChangeDao.RetrieveListChangeDaoRequestByDao(out totalRecord, currentUser, listChangeDaoId, Filter, pageSize, pageIndex, Request.Sort);
                }
                else
                {
                    listUser = Providers.ChangeDao.RetrieveListChangeDaoRequest(out totalRecord, currentUser, Filter, pageSize, pageIndex, Request.Sort);
                }
                if (listUser == null)
                {
                    response.ErrorMessage = string.Format("Can not found user with Dao={0}", currentUser.Dao);
                    response.IsSuccess = false;
                }
                else
                {
                    List<ChangeDaoRequestRecord> records = listUser.Select(x => new ChangeDaoRequestRecord
                    {
                        Id = x.Id,
                        Pic = x.Pic,
                        Reason = x.Reason,
                        Status = x.Status,
                        CreatedDate = x.CreatedDate,
                        ReasonDescription = x.ReasonDescription,
                        Zone = x.Branch.Region,
                        Branch = x.Branch.BranchNameSme,
                        IsDeviation = x.IsDeviation == 1,
                        NeedApprove = (((currentUser.GroupIdentifier.Equals("3") && SystemConfiguration.PostionHeadBranch.Contains(currentUser.Position)) || currentUser.GroupIdentifier.Equals("2")) && x.Status == (int)StatusChangeDaoEnum.Request) || (x.Status == (int)StatusChangeDaoEnum.Create && x.Pic.Equals(currentUser.UserName)) || ((SystemConfiguration.UserHOApprovedDao.Contains(currentUser.UserName) || SystemConfiguration.UserMBDApprovedDao.Contains(currentUser.UserName)) && x.Status == (int)StatusChangeDaoEnum.BranchApproved),
                        CanReject = (x.Status == (int)StatusChangeDaoEnum.Create || x.Status == (int)StatusChangeDaoEnum.Request && x.Pic == currentUser.UserName) || ((currentUser.GroupIdentifier.Equals("2") || SystemConfiguration.PostionHeadBranch.Contains(currentUser.Position)) && (x.Status == (int)StatusChangeDaoEnum.Create || x.Status == (int)StatusChangeDaoEnum.Request)) || ((x.Status == (int)StatusChangeDaoEnum.BranchApproved || x.Status == (int)StatusChangeDaoEnum.RegionApproved) && (SystemConfiguration.UserHOApprovedDao.Contains(currentUser.UserName) || SystemConfiguration.UserMBDApprovedDao.Contains(currentUser.UserName))) || (x.Status == (int)StatusChangeDaoEnum.HOApproved && SystemConfiguration.UserBICApprovedDao.Contains(currentUser.UserName)),
                        RejectPerson = string.IsNullOrEmpty(x.RejectPerson) ? string.Empty : x.RejectPerson + " "
                    }).ToList();
                    response.Records = records;
                    response.Page = new PageRecord
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalRecords = totalRecord,
                    };
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                response.ErrorMessage = string.Format("Can not found user with Dao={0}", Request.CurrentUser.Dao);
                response.IsSuccess = false;
            }
            return isSuccess;
        }
    }
}
